#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>

struct msgbuf
{
	long type;
	char text[1024];
};

int main(int argc, const char *argv[])
{
	key_t key1=ftok("../namepipe/pipe1",'s');
	key_t key2=ftok("../namepipe/pipe2",'s');
/*
	if(key1==-1)
	{
		printf("get key error\n");
	}
*/
	int msgid=msgget(key2,IPC_CREAT|0664);
	int recgid=msgget(key1,IPC_CREAT|0664);
/*	
	if(-1==msgid)
	{
		printf("get msgid error\n");
	}
	else
	{
		printf("msgid success\n");
	}
*/
	struct msgbuf mytext;
	struct msgbuf recvtext;
	mytext.type=1;
	recvtext.type=1;
	pid_t pid=fork();
	char myinput[1024];
	if(pid==0)
	{
		while(1)
		{
			scanf("%s",myinput);
//			strcpy(mytext.text,myinput);
			sprintf(mytext.text,myinput);
			if(-1==msgsnd(msgid,&mytext,sizeof(mytext)-sizeof(long),0))
			{
				printf("msgsnd error\n");
			}
			sleep(1);
		}
	}
	else if(pid>0)
	{
		while(1)
		{
			msgrcv(recgid,&recvtext,sizeof(recvtext)-sizeof(long),1,0);
			printf("1:%s\n",recvtext.text);
		}
	}

	msgctl(msgid,IPC_RMID,0);
	msgctl(recgid,IPC_RMID,0);

	return 0;
}
